<%--
  Created by IntelliJ IDEA.
  User: lt
  Date: 2018/6/21
  Time: 21:25
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://shiro.apache.org/tags" prefix="shiro" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"></c:set>
<c:set var="id" value="${pageContext.request.getParameter('id')}"></c:set>
<title>门店 - 损益单详情</title>
<link rel="stylesheet" href="${contextPath}/static/ace/components/_mod/jquery-ui/jquery-ui.css"/>
<link rel="stylesheet" href="${contextPath}/static/ace/components/bootstrap-datepicker/dist/css/bootstrap-datepicker3.css"/>
<link rel="stylesheet" href="${contextPath}/static/ace/components/_mod/jqgrid/ui.jqgrid.css"/>
<script src="${contextPath}/static/statistics/js/bootstrap-datetimepicker.min.js"></script>
<script src="${contextPath}/static/statistics/js/bootstrap-datetimepicker.zh-CN.js"></script>
<script src="${contextPath}/static/statistics/js/vue.js"></script>
<script src=${contextPath}/static/layer/layui.all.js></script>
<script src="${contextPath}/static/countjs/regularYz.js"></script>
<!-- input 自动补全 -->
<script type="text/javascript" src="${contextPath}/static/statistics/js/jquery.autocomplete.js"></script>
<!-- form表单处理 -->
<script type="text/javascript" src="${contextPath}/static/franchisee/form.js"></script>
<%--<jsp:include page="../../head.jsp"/>--%>
<style type="text/css">
    .customBtn {
        line-height: 20px;
        margin-bottom: 3px;
    }

    .btnLine {
        margin-left: 1px;
        margin-top: 8px;
        margin-bottom: 2px;
    }

    @-webkit-keyframes bouncedelay {
        0%, 80%, 100% {
            -webkit-transform: scale(0.0)
        }
        40% {
            -webkit-transform: scale(1.0)
        }
    }

    @keyframes bouncedelay {
        0%, 80%, 100% {
            transform: scale(0.0);
            -webkit-transform: scale(0.0);
        }
        40% {
            transform: scale(1.0);
            -webkit-transform: scale(1.0);
        }
    }

    .autocomplete-suggestions {
        border: 1px solid #999;
        background: #FFF;
        overflow: auto;
    }

    .autocomplete-suggestion {
        padding: 2px 5px;
        white-space: nowrap;
        overflow: hidden;
    }

    .autocomplete-selected {
        background: #F0F0F0;
    }

    .autocomplete-suggestions strong {
        font-weight: normal;
        color: #3399FF;
    }

    @-moz-document url-prefix() {
        fieldset {
            display: table-cell;
        }
    }

    .ui-jqgrid .ui-priority-secondary{
        background: #d5effc;
    }

    .ui-jqgrid .ui-jqgrid-title{font-size:12px;}    /*修改grid标题的字体大小*/

    .ui-jqgrid-sortable {font-size:12px;}   /*修改列名的字体大小*/

    .ui-jqgrid tr.jqgrow td {font-size:12px; font-family:"宋体"} /*修改表格内容字体*/

    /*****  表头样式  ******/
    /*.ui-jqgrid .ui-jqgrid-titlebar{*/
    /*background-color: #878787;*/
    /*height: 36px;*/
    /*}*/
    /*****  标题样式  ******/
    .ui-jqgrid-sortable {
        text-align: center;
    }

    #cb_grid-coupontype-table{
        margin-left: 9px;
    }
    #grid-coupontype-table_rn {
        width: 36px;
    }

    #myModal .modal-body table tr{
        height: 30px;
    }
    #myModal .modal-body table input[type='text']{
        height: 22px;
    }
    #myModal .modal-body table select {
        height: 22px;
    }

    .popover-content{
        color: red;
    }

    #cb_grid-lossprofitltem-table{
        margin-left: 10px;
    }
    #cb_list2{
        margin-left: 10px;
    }

    label{
        font-size: 13px;
    }

    .ui-pg-div{
        display: none;
    }

</style>

<div class="row" id="app">
    <div class="row btnLine">
        <div class="button-len col-sm-12">
            <form class="form-inline layui-form ">
                <div class="form-group">
                    <a class="btn btn-white btn-success btn-sm customBtn" onclick="goBack()">
                        <i class="ace-icon fa fa-reply blue"> 返回</i>
                    </a>
                </div>
                <div class="form-group">
                    <button class="btn btn-white btn-success btn-sm customBtn" type="button" onclick="confirmShopLossProfit()">
                        <i class="ace-icon fa fa-check blue"> 确定损益单</i>
                    </button>
                </div>
            </form>
        </div>
    </div>
    <br/>
    <!-- 内容数据开始 -->
    <div class="col-xs-12">
        <table id="grid-lossprofitltem-table"></table>

        <div id="grid-lossprofitltem-pager"></div>

    </div>
    <!-- 内容数据结束 -->
</div>


<!-- 公用变量 -->
<script type="text/javascript">
    var lastSel;//在顶部定义
    var grid_lossprofitltem_selector = "#grid-lossprofitltem-table";
    var pager_lossprofitltem_selector = "#grid-lossprofitltem-pager";

    var laypage = layui.laypage,
        layer = layui.layer
    laydate = layui.laydate;

    var laypage = layui.laypage,
        layer = layui.layer
    laydate = layui.laydate;

    var app = new Vue({
        el: '#app',
        data: {
            boxObj: [],   //列名称集合
        },
    });


</script>

<!-- 方法调用（业务） -->
<script type="text/javascript">
    //    var alertMoble = function () {
    //        pageInit()
    //        $("#authorizationInfoContent").removeClass("hide")
    //        modalIndex = layer.open({
    //            type: 1,
    //            title: '盘点批号选择',
    //            closeBtn: 1,
    //            shadeClose: true,
    //            maxmin: true,
    //            area: ['635px', '440px'],
    //            skin: 'yourclass',
    //            content: $("#authorizationInfoContent"),
    //            end: function () {
    //                $("#authorizationInfoContent").addClass("hide")
    //            }
    //        });
    //    }
    //确定损益单
    var confirmShopLossProfit = function () {
        layer.load(1);
        var takeObj = {};
        var prodList = [];
        var ids = $(grid_lossprofitltem_selector).getDataIDs();
        if(ids.length <= 0){
            layer.closeAll('loading');
            layer.msg('提示：请选择商品',{icon:0})
            return;
        }
        for(var i = 0; i < ids.length; i++){
            var id = ids[i];
            if(id){
                $(grid_lossprofitltem_selector).jqGrid('saveRow', lastSel, '');
                lastSel = id;
            }
            var rowData = $(grid_lossprofitltem_selector).jqGrid('getRowData', id);
            if(rowData.state == '1'){
                layer.closeAll('loading');
                layer.msg('提示：损益单已经处理！',{icon: 0});
                return;
            }

            takeObj.shopId = rowData.shopId;
            takeObj.orderId = rowData.orderId;
            rowData.state = '1';
            prodList.push(rowData);
        }
        takeObj.prodList = JSON.stringify(prodList);

        console.log(takeObj)

        $.ajax({
            url: '${contextPath}/ktTakeStock/confirmShopLossProfit',
            type: 'post',
            dataType: 'json',
            data: takeObj,
            success: function (data) {
                console.log(data.code)
                if(data.code != 000){
                    layer.closeAll('loading');
                    layer.msg(data.message, {icon: 0});
                }
                reload();
                layer.closeAll('loading');
                layer.msg('操作成功', {icon: 1})
            },
            error: function (error) {
                layer.closeAll('loading');
                layer.msg('网络错误', {icon: 0})
            }
        })
    }

    //获取店铺
    var getShop = function () {
        var shopId = '';
        var shopName = '';
        var shopQuery = {};
        var filters = {
            "rules": [
                {
                    "field": "type",
                    "data": 'kt'
                },
                {
                    "field" : "state",
                    "data": '1'
                }
            ]
        };
        shopQuery.shopType = "'加盟', '直营'";
        shopQuery.filters = JSON.stringify(filters);
        shopQuery.state = '5';
        $.ajax({
            url: '${contextPath}/ktCommon/getShopList2User',
            type: 'post',
            data: shopQuery,
            success: function (data) {
                var shopArray = []
                for(var i = 0; i < data.length; i++){
                    var shop = {}
                    shop.value = data[i].shopName;
                    shop.data = data[i].shopId;
                    shopArray.push(shop);
                    shopId = data[i].shopId;
                    shopName = data[i].shopName;
                }
                $('#shopId').val(shopId);
                $('#shopName').val(shopName);
                var countries = shopArray
                $('#shopName').autocomplete({
                    lookup: countries,
                    onSelect: function (suggestion) {
//                         alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
                        $('#shopId').val(suggestion.data);
                    },
                    minChars: 0,
                });
                getKtTakeAnalysis(shopId);  //加载数据
            },
            error: function (error){
                getKtTakeAnalysis(shopId);  //加载数据
                layer.msg("获取出错："+data.message, {icon: 0})
            }
        })
    }

    //时间格式方法
    var format = function(date,str){
        var mat={};
        mat.M=date.getMonth()+1;//月份记得加1
        mat.H=date.getHours();
        mat.s=date.getSeconds();
        mat.m=date.getMinutes();
        mat.Y=date.getFullYear();
        mat.D=date.getDate();
        mat.d=date.getDay();//星期几
        mat.d=check(mat.d);
        mat.H=check(mat.H);
        mat.M=check(mat.M);
        mat.D=check(mat.D);
        mat.s=check(mat.s);
        mat.m=check(mat.m);
        if(str.indexOf(":")>-1){
            mat.Y=mat.Y.toString().substr(2,2);
            return mat.Y+"/"+mat.M+"/"+mat.D;
        }
        if(str.indexOf("/")>-1){
            return mat.Y+"/"+mat.M+"/"+mat.D+" "+mat.H+"/"+mat.m+"/"+mat.s;
        }
        if(str.indexOf("-")>-1){
            return mat.Y+"-"+mat.M+"-"+mat.D+ " "+mat.H+":"+mat.m+":"+mat.s;
        }
        if(str.indexOf("_")>-1){
            return mat.Y+"-"+mat.M+"-01 00:00:00";
        }
        if(str.indexOf("|")>-1){
            return mat.Y+"-"+mat.M+"-"+mat.D;
        }
    }
    //检查是不是两位数字，不足补全
    var check = function(str){
        str=str.toString();
        if(str.length<2){
            str='0'+ str;
        }
        return str;
    }

    var goBack = function(){
        javascript:window.history.go(-1);window.close();
    }

    //页面加载
    $(function () {
        layer.load(1);
        getShop();
        var time = format(new Date(),"yyyy|MM|dd");
        $('#date').val(time);
        layer.closeAll('loading');
    })

</script>

<!-- jqGrid 公用方法 -->
<script type="application/javascript">

    function style_edit_form(form) {
        //enable datepicker on "sdate" field and switches for "stock" field
        //form.find('input[name=sdate]').datepicker({format:'yyyy-mm-dd' , autoclose:true})

        //form.find('input[name=stock]').addClass('ace ace-switch ace-switch-5').after('<span class="lbl"></span>');
        //don't wrap inside a label element, the checkbox value won't be submitted (POST'ed)
        //.addClass('ace ace-switch ace-switch-5').wrap('<label class="inline" />').after('<span class="lbl"></span>');


        //update buttons classes
        var buttons = form.next().find('.EditButton .fm-button');
        buttons.addClass('btn btn-sm').find('[class*="-icon"]').hide();//ui-icon, s-icon
        buttons.eq(0).addClass('btn-primary').prepend('<i class="ace-icon fa fa-check"></i>');
        buttons.eq(1).prepend('<i class="ace-icon fa fa-times"></i>')

        buttons = form.next().find('.navButton a');
        buttons.find('.ui-icon').hide();
        buttons.eq(0).append('<i class="ace-icon fa fa-chevron-left"></i>');
        buttons.eq(1).append('<i class="ace-icon fa fa-chevron-right"></i>');
    }

    function style_delete_form(form) {
        var buttons = form.next().find('.EditButton .fm-button');
        buttons.addClass('btn btn-sm btn-white btn-round').find('[class*="-icon"]').hide();//ui-icon, s-icon
        buttons.eq(0).addClass('btn-danger').prepend('<i class="ace-icon fa fa-trash-o"></i>');
        buttons.eq(1).addClass('btn-default').prepend('<i class="ace-icon fa fa-times"></i>')
    }

    function style_search_filters(form) {
        form.find('.delete-rule').val('X');
        form.find('.add-rule').addClass('btn btn-xs btn-primary');
        form.find('.add-group').addClass('btn btn-xs btn-success');
        form.find('.delete-group').addClass('btn btn-xs btn-danger');
    }

    function style_search_form(form) {
        var dialog = form.closest('.ui-jqdialog');
        var buttons = dialog.find('.EditTable')
        buttons.find('.EditButton a[id*="_reset"]').addClass('btn btn-sm btn-info').find('.ui-icon').attr('class', 'ace-icon fa fa-retweet');
        buttons.find('.EditButton a[id*="_query"]').addClass('btn btn-sm btn-inverse').find('.ui-icon').attr('class', 'ace-icon fa fa-comment-o');
        buttons.find('.EditButton a[id*="_search"]').addClass('btn btn-sm btn-purple').find('.ui-icon').attr('class', 'ace-icon fa fa-search');
    }

    function beforeDeleteCallback(e) {
        var form = $(e[0]);
        if (form.data('styled')) return false;

        form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
        style_delete_form(form);
        form.data('styled', true);
    }

    function beforeEditCallback(e) {
        var form = $(e[0]);
        form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
        style_edit_form(form);
    }


    //it causes some flicker when reloading or navigating grid
    //it may be possible to have some custom formatter to do this as the grid is being created to prevent this
    //or go back to default browser checkbox styles for the grid
    function styleCheckbox(table) {
        /**
         $(table).find('input:checkbox').addClass('ace')
         .wrap('<label />')
         .after('<span class="lbl align-top" />')


         $('.ui-jqgrid-labels th[id*="_cb"]:first-child')
         .find('input.cbox[type=checkbox]').addClass('ace')
         .wrap('<label />').after('<span class="lbl align-top" />');
         */
    }


    //unlike navButtons icons, action icons in rows seem to be hard-coded
    //you can change them like this in here if you want
    function updateActionIcons(table) {
        /**
         var replacement =
         {
             'ui-ace-icon fa fa-pencil' : 'ace-icon fa fa-pencil blue',
             'ui-ace-icon fa fa-trash-o' : 'ace-icon fa fa-trash-o red',
             'ui-icon-disk' : 'ace-icon fa fa-check green',
             'ui-icon-cancel' : 'ace-icon fa fa-times red'
         };
         $(table).find('.ui-pg-div span.ui-icon').each(function(){
				var icon = $(this);
				var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
				if($class in replacement) icon.attr('class', 'ui-icon '+replacement[$class]);
			})
         */
    }

    //replace icons with FontAwesome icons like above
    function updatePagerIcons(table) {
        var replacement =
            {
                'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',
                'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',
                'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',
                'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'
            };
        $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
            var icon = $(this);
            var $class = $.trim(icon.attr('class').replace('ui-icon', ''));

            if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
        })
    }

    function enableTooltips(table) {
        $('.navtable .ui-pg-button').tooltip({container: 'body'});
        $(table).find('.ui-pg-div').tooltip({container: 'body'});
    }

    //var selr = jQuery(grid_selector).jqGrid('getGridParam','selrow');

//    $(document).one('ajaxloadstart.page', function (e) {
//        $.jgrid.gridDestroy(grid_lossprofitltem_selector);
//        $('.ui-jqdialog').remove();
//    });

    //重新加载数据
    var reload = function () {
        var filters = {};
        filters.shopId = $('#shopId').val();
        filters.date = $('#date').val();

        $(grid_lossprofitltem_selector).jqGrid('setGridParam',{
            url:"${contextPath}/ktTakeStock/getShopLossProfitItems",
            datatype:'json',
            postData: filters,
        }).trigger("reloadGrid"); //重新载入
    }
</script>

<!-- jqGrid加载数据 -->
<script type="text/javascript">
    var scripts = [null, "${contextPath}/static/ace/components/bootstrap-datepicker/dist/js/bootstrap-datepicker.js", "${contextPath}/static/ace/components/jqGrid/js/jquery.jqGrid.js", "${contextPath}/static/ace/components/jqGrid/js/i18n/grid.locale-cn.js", "${contextPath}/static/layer/layer.js","${contextPath}/static/ztree/js/jquery.ztree.core-3.5.js", "${contextPath}/static/ztree/js/jquery.ztree.excheck-3.5.js", null]

    var getKtTakeAnalysis = function () {
        var filters = {};
        filters.id = '${id}';

        $('.page-content-area').ace_ajax('loadScripts', scripts, function () {
            jQuery(function ($) {
                jQuery(grid_lossprofitltem_selector).jqGrid({
                    url: "${contextPath}/ktTakeStock/getShopLossProfitItems",
                    datatype: "json",
                    postData: filters,
                    mtype: 'POST',
                    height: 500,
                    colNames : ['商品名称', '商品条码', '数量', '创建人员ID', '创建人员', '创建时间','审核人员Id', '审核人员','审核时间', '状态id', '状态','shopId', 'orderId'],
                    colModel : [
                        {
                            name: 'productName',
                            index: 'productName',
                            width: 230,
                            editable: false,
                            sortable: false,
                            editrules: {required: true}
                        },
                        {
                            name: 'productCode',
                            index: 'productCode',
                            editable: false,
                            sortable: false,
                            editrules: {required: true}
                        },
                        {
                            name: 'quantity',
                            index: 'quantity',
                            editable: false,
                            dataType: 'int',
                            sortable: false,
                            editrules: {required: true}
                        },
                        {
                            name: 'createUser',
                            index: 'createUser',
                            editable: false,
                            sortable: false,
                            hidden:true
                        },
                        {
                            name: 'userName',
                            index: 'userName',
                            editable: false,
                            sortable: false
                        },
                        {
                            name: 'createTime',
                            index: 'createTime',
                            editable: false,
                            sortable: false
                        },
                        {
                            name: 'modifyUser',
                            index: 'modifyUser',
                            dataType: 'int',
                            editable: false,
                            sortable: false,
                            hidden:true
                        },
                        {
                            name: 'modifyUserName',
                            index: 'modifyUserName',
                            dataType: 'int',
                            editable: false,
                            sortable: false
                        },
                        {
                            name: 'modifyTime',
                            index: 'modifyTime',
                            //                        width: 60,
                            editable: false,
                            sortable: false
                        },
                        {name : 'state',index : 'state', editable: false, align: 'center', hidden: true},
                        {name : 'stateName',index : 'stateName', editable: false, align: 'center',
                            formatter: function (v, x, r) {
                                var state = r.state;
                                console.log(state)
                                var stateName = '<i class="ace-icon fa fa-times blue">';
                                if(state == 1){
                                    stateName = '<i class="ace-icon fa fa-check blue">';
                                }
                                return stateName;
                            }
                        },
                        {name: 'shopId', index: 'shopId', hidden: true},
                        {name: 'orderId', index: 'orderId', hidden: true},
                    ],
                    rownumbers: true, //自动行数

                    autowidth:true,  //宽度自适应
                    viewrecords: true,
                    rowNum : 1000000,//一页显示多少条
                    //                rowList : [ 10, 20, 30 ],//可供用户选择一页显示多少条
                    //                pager : pager_lossprofitltem_selector,//表格页脚的占位符(一般是div)的id
                    sortname : 'gmtModifiedStr',//初始化的时候排序的字段
                    sortorder : "desc",//排序方式,可选desc,asc
                    altRows: true,
                    multiselect: false,
                    multiboxonly: false,

                    loadComplete: function () {
                        var table = this;
                        setTimeout(function () {
                            styleCheckbox(table);
                            updateActionIcons(table);
                            updatePagerIcons(table);
                            enableTooltips(table);
                        }, 0);
                    },

                    editurl: "${contextPath}/ktSaleProject/saveSaleProject",//nothing is saved
                    caption: "盘点分析列表",
                    jsonReader: {
                        root: "recordList",
                        page: "currentPage",
                        total: "pageCount",
                        records: "recordCount"
                    },

                    gridComplete : function() {
                        var ids = jQuery(grid_lossprofitltem_selector).jqGrid('getDataIDs');
                        for (var i = 0; i < ids.length; i++) {
                            var cl = ids[i];
                            be = '<a style="height:22px;width:20px;" type="button" onclick="">+</a>&nbsp;&nbsp;';
                            se = '<a style="height:22px;width:20px;" type="button" onclick="" >-</a>';
                            jQuery(grid_lossprofitltem_selector).jqGrid('setRowData', ids[i],
                                {
                                    cardNo: be + se
                                });
                        }
                    },

                    ondblClickRow: function (id, e) {
                        console.log(id)
                        if(id && id!==lastSel){
                            $(grid_lossprofitltem_selector).jqGrid('saveRow', lastSel, '');
                            lastSel = id;
                        }
                        $(grid_lossprofitltem_selector).jqGrid('editRow', id)
                    },

                    //行编辑框
                    beforeSelectRow: function (id, e) {
                        if(id && id!==lastSel){
                            $(grid_lossprofitltem_selector).jqGrid('saveRow', lastSel, '');
                            lastSel = id;
                        }
                        //                    $(grid_lossprofitltem_selector).jqGrid('editRow', id)
                    }, //加上grid代码处。
                });

                jQuery(grid_lossprofitltem_selector).jqGrid('navGrid', '#addpager', {
                    edit : false,
                    add : false,
                    del : false,
                    search : false
                });

                $(window).triggerHandler('resize.jqGrid');//trigger window resize to make the grid get the correct size

                $("#jqgh_grid-coupontype-table_rn").html('');
                $("#grid-coupontype-table_rn").css('width', '36px');
            });
        });
    }
</script>
<!-- 控件 -->
<script type="text/javascript">
    //时间
    $('#date').datetimepicker({
        minView: "month", //选择日期后，不会再跳转去选择时分秒
        language: 'zh-CN',  //汉化
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
//        startView: 2,
        forceParse: 0,
        minView: 2,
        showMeridian: 1,
        format: "yyyy-mm-dd", //选择日期后，文本框显示的日期格式
        autoclose:true, //选择日期后自动关闭
        minuteStep:1,
//        startDate:new Date(),
    });
</script>